#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhengpingping

import os
import re
import sys
import shutil

import codecs
import operator
import importlib
importlib.reload(sys)
pattern = "^[a-zA-Z$_]+[a-zA-Z0-9$_]*$"

# 定义Excel数据结构
class ExcelData:
    fieldName = ''
    fieldType = ''
    fieldDesc = ''
    platform = ''

    def __init__(self, idx):
        self.fieldIdx = idx

# 验证平台类型
def check_platform(platform):
    return platform == 'client' or platform == 'both'

# 验证文件名合法性
def check_fileName(fileName, search_names):
    result = re.match(pattern, fileName)
    contain = operator.contains(search_names, fileName)
    return not contain and result

# 验证数组类型
def valid_check_array(value):
    list = str(value).split(',')
    for item in list:
        if(not item.isdigit()):
            return False
    return True

# 验证值类型 ctype : 0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error
def valid_check_value(value, typeRow):
    if typeRow == 'bool':
        return isinstance(value, int) or not value
    elif typeRow == 'int':
        return isinstance(value, int) or not value
    elif typeRow == 'array_int':
        return valid_check_array(value)
    return True

#创建目录
def create_dir(folder):
    if os.path.isdir(folder):
        shutil.rmtree(folder)
    os.makedirs(folder)

#保存文件
def save_file(file_path, string):
    f = codecs.open(file_path, "w", "utf-8")
    f.write(string)
    f.close()

# 获取单元格值
def get_cell_value(ws, row, col):
    cell = ws.cell(row, col)
    cell_value = cell.value

    if cell.ctype == 2 and cell_value % 1 == 0:
        cell_value = int(cell_value)
    return cell_value

# 读取excel文件
def excel_sheet_read(ws) -> list[ExcelData]:
    search_line = []
    field_names = []

    for i in range(ws.ncols):
        temp = ExcelData(i)
        temp.platform = ws.cell_value(0, i)
        temp.fieldType = ws.cell_value(1, i)
        temp.fieldName = ws.cell_value(2, i)
        temp.fieldDesc = ws.cell_value(3, i)

        contain = operator.contains(field_names, temp.fieldName)
        if(contain or not re.match(pattern, temp.fieldName)):
            tempStr = "{0}=={1}=={2} is invalid"
            print(tempStr.format(str(i), temp.fieldName, temp.fieldType))  
            continue
        
        if(check_platform(temp.platform)):
            field_names.append(temp.fieldName)
            search_line.append(temp)
    return search_line

# 初始化方法
def init(outPath, excel_sheet_read):
    create_dir(outPath) 
    print('Start Create File')
    
    for root, dirs, files in os.walk('Xlsx/'):
        for filename in files:
            name, ext = os.path.splitext(filename)
            print(filename + ' translate start')

            if ext == '.xlsx' or ext == '.xls':
                file = root + '/' + filename
                excel_sheet_read(file)
    print("Create File Succeed!!!")

# os.system('pause')
# sys.exit(0)